package com.yej.aiPolice.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.SystemClock
import android.text.TextUtils
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import cn.smssdk.EventHandler
import cn.smssdk.SMSSDK
import cn.smssdk.SMSSDK.getVerificationCode
import cn.smssdk.SMSSDK.submitVerificationCode
import com.yej.aiPolice.R
import com.yej.aiPolice.presenter.LoginActivityPresenter
import com.yej.aiPolice.ui.activity.web.RegisterActivity
import com.yej.aiPolice.util.SMSUtil
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class LoginActivity : AppCompatActivity() {



    var phone:String? = null
    var code:String? = null

    val eh = object : EventHandler() {

        override fun afterEvent(event: Int, result: Int, data: Any) {

            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    Log.e("sms","提交验证码成功")
                    //TODO 为了测试暂时屏蔽
//                    loginActivityPresenter.loginByPhone(phone!!,code!!)
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    Log.e("sms","获取验证码成功")
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                }
            } else {
                Log.e("sms","出现错误 错误描述 ${ (data as Throwable).message}")
                (data as Throwable).printStackTrace()
            }
        }
    }

    lateinit var loginActivityPresenter: LoginActivityPresenter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        Log.e("log","挂载成功")
        loginActivityPresenter = LoginActivityPresenter(this)
        initListener()
        SMSSDK.registerEventHandler(eh) //注册短信回调
    }

    override fun onDestroy() {
        super.onDestroy()
        SMSSDK.unregisterEventHandler(eh)

    }
        private fun initListener() {
            iv_user_back.setOnClickListener { finish() }
            tv_user_code.setOnClickListener {
                phone = et_user_phone.text.toString().trim()
                if(SMSUtil.isMobile(phone)){
                    Log.e("sms","开始获取验证码 手机号码 ${phone}")
                    getVerificationCode("86",phone)
                    //开启倒计时
                    tv_user_code.isEnabled = false
                    Thread(CutDownTask()).start()
                }

            }
            iv_login.setOnClickListener {
                 phone = et_user_phone.text.toString().trim()
                 code = et_user_code.text.toString().trim()

                // TODO 为了测试先放这 正式要取消
                loginActivityPresenter.loginByPhone(phone!!,code!!)

                Log.e("sms","手机号:${phone} 验证码${code} ${SMSUtil.isMobile(phone) && TextUtils.isEmpty(code)}")
                if(SMSUtil.isMobile(phone) && !TextUtils.isEmpty(code)){
                    Log.e("sms","手机号:${phone} 验证码${code}")
                    submitVerificationCode("86",phone,code)
                }

            }
            iv_register.setOnClickListener {
                startActivity<RegisterActivity>()
            }
        }

    fun onLoginSuccess() {
        finish()
        toast("登陆成功")

    }

    fun onLoginFail(){
        toast("登陆失败")
    }

    companion object{
        const val TIME_MINUS:Int = -1
        const val TIME_IS_OUT:Int = 0
    }

    val handler = @SuppressLint("HandlerLeak")
    object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg!!.what){
                TIME_MINUS -> tv_user_code.text = "剩余时间($time)秒"
                TIME_IS_OUT -> {
                    tv_user_code.text = "点击重新发送"
                    time = 60
                    tv_user_code.isEnabled = true

                }
            }
        }
    }
    var time = 60
    inner class CutDownTask :Runnable{
        override fun run() {
            while(time > 0){
                // 刷新剩余时间，当前子线程，使用handler
                handler.sendEmptyMessage(TIME_MINUS)
                SystemClock.sleep(1000) //睡眠1秒
                time --
            }
            handler.sendEmptyMessage(TIME_IS_OUT)
        }

    }
}
